import { defineStore } from 'pinia'
import Cookies from 'js-cookie'
import { get, post } from '@/utils/request'
import type { User } from '@/types'

interface UserState {
  username: string
  token: string
  userInfo: User | null
  permissions: string[]
}

export const useUserStore = defineStore('user', {
  state: (): UserState => ({
    username: '',
    token: Cookies.get('Admin-Token') || '',
    userInfo: null,
    permissions: []
  }),
  
  getters: {
    isLogin: (state) => !!state.token && !!state.userInfo,
    hasPermission: (state) => (permission: string) => {
      if (state.permissions.includes('*')) {
        return true
      }
      return state.permissions.includes(permission)
    }
  },
  
  actions: {
    // 登录
    async login(username: string, password: string) {
      // mock 登录逻辑
      this.username = username
      this.token = 'mock-token'
      Cookies.set('Admin-Token', 'mock-token', { expires: 7 })
      return { data: { token: 'mock-token' }, code: 0, message: '登录成功' }
    },
    
    // 获取用户信息
    async getUserInfo() {
      // mock 用户信息，补全所有 User 类型字段
      this.userInfo = {
        id: '1',
        username: this.username,
        realName: '超级管理员',
        avatar: '',
        email: '',
        phone: '',
        role: {
          id: '1',
          name: 'admin',
          description: '超级管理员',
          permissions: ['*'],
          createdAt: '',
          updatedAt: ''
        },
        status: 'active',
        permissions: ['*'],
        createdAt: new Date().toISOString(),
        lastLogin: new Date().toISOString()
      }
      this.permissions = ['*']
      return this.userInfo
    },
    
    // 退出登录
    async logout() {
      try {
        // 调用退出登录接口
        await post('/admin/logout')
      } catch (error) {
        console.error('退出登录失败:', error)
      } finally {
        // 无论接口调用成功与否，都清除本地状态
        this.token = ''
        this.userInfo = null
        this.permissions = []
        Cookies.remove('Admin-Token')
      }
    },
    
    // 重置状态
    resetState() {
      this.token = ''
      this.userInfo = null
      this.permissions = []
    }
  }
}) 